package com.bd.scm.module.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bd.offices.excel.ExcelUtil;
import com.bd.scm.domain.dto.aggrid.AgGridRequest;
import com.bd.scm.domain.dto.aggrid.AgGridResponse;
import com.bd.scm.domain.dto.user.PersonnelFilesDto;
import com.bd.scm.domain.dto.user.UserDto;
import com.bd.scm.domain.dto.user.UserOfLeaveBatchDto;
import com.bd.scm.domain.models.leave.LeaveTypeDefinition;
import com.bd.scm.domain.models.user.DtUser;
import com.bd.scm.domain.models.user.UserInfo;
import com.bd.scm.domain.models.user.UserVacation;
import com.bd.scm.module.common.BaseController;
import com.bd.scm.module.enums.ExceptionEmun;
import com.bd.scm.module.user.service.IDtUserService;
import com.bd.scm.module.user.service.UserInfoService;
import com.bd.scm.module.user.service.UserVacationService;
import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.FileUtil;
import com.bd.utils.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户前端控制器
 * User: _Cps
 * Date: 2019.08.28 16:44
 */
@Slf4j
@Api("员工假期接口")
@RestController
@RequestMapping("/api/vacation")
public class UserVacationController extends BaseController {

    @Autowired
    private UserVacationService userVacationService;

    /**
     * 分页获取假期信息.
     *
     * @param userVacation 条件
     * @return 人员信息集合
     */
    @RequestMapping("vacationList")
    @ResponseBody
    public Result vacationList(@RequestBody UserVacation userVacation) {
//        Result<AgGridResponse> result = new Result<AgGridResponse>();
//        //之后要根据传值，
//        UserVacation userVacation = JSON.parseObject(JSON.toJSONString(request.getData()),
//                UserVacation.class);
//        Page<UserVacation> page = getPage(request);
//        ;
//        IPage<UserVacation> pageList = this.userVacationService.vacationList(page, userVacation);
//        AgGridResponse<UserVacation> response = getResponse(request, pageList, page);
//        result.setSuccess(true);
//        result.setResult(response);
//        return result;

        log.info("vacationList params: {}", JSON.toJSON(userVacation));
        Result result = null;
        try {
            if(userVacation == null){
                userVacation = new UserVacation();
            }
            List<UserVacation> list = this.userVacationService.vacationList(userVacation);
            result = ResultUtil.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }



    /**
     * 修改
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/updateJqInfo")
    public Result updateJqInfo(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.userVacationService.updateJqInfo(userVacation, clientIp);
        if (flag > 0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR_UPDATE);
        }
    }


    /**
     * 锁定假期
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/sockVacation")
    @ResponseBody
    public Result sockVacation(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.userVacationService.sockVacation(userVacation, clientIp);
        if (flag >0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.USER_ERROR_sock);
        }
    }
    /**
     * 设置调休上限
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/setLimit")
    @ResponseBody
    public Result setLimit(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        System.out.println(userVacation);
        int flag = this.userVacationService.setLimit(userVacation, clientIp);
        if (flag >0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.USER_ERROR_sock);
        }
    }


    /**
     * 清零上年法定年假
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/fdClearingZero")
    public Result clearingZero(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.userVacationService.clearingZero(userVacation, clientIp);
        if (flag >0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR_UPDATE);
        }
    }
    /**
     * 清零当年福利年假
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/flClearingZero")
    public Result flclearingZero(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.userVacationService.flClearingZero(userVacation, clientIp);
        if (flag >0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR_UPDATE);
        }
    }

    /**
     * 录入
     *
     * @param userVacation 条件
     * @return
     */
    @RequestMapping("/luRuVacation")
    public Result luRuVacation(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.userVacationService.luRuVacation(userVacation, clientIp);
        if (flag >0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR_UPDATE);
        }
    }


    /**
     * 年假导入
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("upJiaQiExcel")
    @ResponseBody
    public Result upLinShiExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = this.userVacationService.upJiaQiExcel(file, request);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 锁定假期导入
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("upLockVacationExcel")
    @ResponseBody
    public Result upLockVacationExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = this.userVacationService.upLockVacationExcel(file, request);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 锁定假期导入
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("upBreakExcel")
    @ResponseBody
    public Result upBreakExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = this.userVacationService.upBreakExcel(file, request);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 年假导入模板
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadTemplate")
    public void downLoad(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "员工假期导入模板" + ".xlsx";
        ServletOutputStream out;
        FileUtil.setResponseHeader(fileName, response);
        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        FileInputStream inputstream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputstream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputstream.close();

        if (out != null) {
            out.flush();
            out.close();
        }
    }
    /**
     * 锁定假期导入模板
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadTemplate2")
    public void downLoad2(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "锁定假期导入模板" + ".xlsx";
        ServletOutputStream out;
        FileUtil.setResponseHeader(fileName, response);
        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        FileInputStream inputstream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputstream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputstream.close();

        if (out != null) {
            out.flush();
            out.close();
        }
    }
    /**
     * 调休导入模板
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadTemplate3")
    public void downLoad3(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "调休导入模板" + ".xlsx";
        ServletOutputStream out;
        FileUtil.setResponseHeader(fileName, response);
        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        FileInputStream inputstream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputstream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputstream.close();

        if (out != null) {
            out.flush();
            out.close();
        }
    }

    /**
     * 假类导出
     *
     * @param serchTxt
     * @param response
     * @return
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "vacationExport")
    public Result vacationExport(String serchTxt,String depSerial,String startDate,HttpServletResponse response) throws IOException, InstantiationException, IllegalAccessException {
        UserVacation userVacation = new UserVacation();
        userVacation.setSerchTxt(serchTxt);
        userVacation.setDepSerial(depSerial);
        if(startDate!=null){
            userVacation.setStartDate(startDate);
        }
        AgGridRequest request = new AgGridRequest();
        request.setStartRow(0);
        request.setEndRow(10000);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("serchTxt",serchTxt);
        map.put("depSerial",depSerial);
        if(depSerial!=null){
            map.put("startDate",startDate);
        }
        request.setData(map);
        Page<UserVacation> page = getPage(request);
        List<UserVacation> doorDefinition = this.userVacationService.vacationList(userVacation);
        ExcelUtil.ExportExcel("导出假类列表" + UUID.randomUUID().toString(), response, doorDefinition, UserVacation.class);
        return ResultUtil.ok();
    }

    /**
     * 查询全局保存法定年假、福利年假清0时间设置
     * @return fdNjClearDate 法定年假清0时间 flNjCleaDate 福利年假清0时间
     */
    @GetMapping("getfdflNjClearDate")
    @ResponseBody
    public Result getfdflNjClearDate() {
        return ResultUtil.ok(this.userVacationService.getfdflNjClearDate());
    }


    /**
     * 全局保存法定年假、福利年假清0时间设置
     * @param userVacation fdNjClearDate 法定年假清0时间 flNjCleaDate 福利年假清0时间
     * @return
     */
    @PostMapping("updatefdflNjClearDate")
    @ResponseBody
    @ApiOperation(value = "修改全局保存法定年假、福利年假清0时间设置", httpMethod = "POST", protocols = "HTTP", notes = "修改全局保存法定年假、福利年假清0时间设置", produces = "application/json")
    public Result updatefdflNjClearDate(@ApiParam(name = "userVacation", value = "人员假期实体类", required = true)
                               @RequestBody UserVacation userVacation, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        String flag = this.userVacationService.updatefdflNjClearDate(userVacation);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }
}
